import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: []
  },
  getters: {
    length(state) {
      return state.cartList.length
    },
    List(state) {
      return state.cartList
    }
  },
  mutations: {
    addNewProduct(state, payload) {
      payload.count = 1
      // 默认在购物车处于选中状态
      payload.checked = true
      state.cartList.push(payload)
    },
    addOldProduct(state, payload) {
      payload.count += 1
    },
    checkClick(state, payload) {
      state.cartList[payload].checked = !state.cartList[payload].checked
    }
  },
  actions: {
    // actions不仅放异步操作，还可以放逻辑判断
    addProduct(context, payload) {
      // 判断要添加的商品在购物车里有没有, 根据iid进行判断
      // 返回值product为数组cartList中相同的那一个对象 或者为空
      return new Promise((resolve) => {
        const product = context.state.cartList.find(item => item.iid === payload.iid)
        if (product) {
          // 有，让count+=1
          context.commit("addOldProduct", product)
          resolve("购物车里该商品 + 1")
        } else {
          // 没有，给product添加count属性，并加入数组
          context.commit("addNewProduct", payload)
          resolve("添加购物车成功")
        }
      })
    }
  },
  modules: {
  }
})
